package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.base.sdk.base.net.CommonObserver;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.promeg.pinyinhelper.Pinyin;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.BaseActivity;
import com.jtlrm.ckd.entity.ShiWuEntity;
import com.jtlrm.ckd.entity.ShiWuSelectEntity;
import com.jtlrm.ckd.entity.ShiWuTypeEntity;
import com.jtlrm.ckd.entity.YinShiDetailAdpterEntity;
import com.jtlrm.ckd.entity.YinShiDetailEntity;
import com.jtlrm.ckd.entity.event.YinShiSelectMessage;
import com.jtlrm.ckd.entity.submitEntity.YinShiData;
import com.jtlrm.ckd.mvp.model.YinShiMode;
import com.jtlrm.ckd.mvp.view.adapter.ShiWuSearchAdapter;
import com.jtlrm.ckd.mvp.view.adapter.ShiWuTypeAdapter;
import com.jtlrm.ckd.util.CommonUtil;
import com.jtlrm.ckd.util.ContactList.FoodListView;
import com.jtlrm.ckd.util.ContactList.SlideBarEntity;
import com.jtlrm.ckd.util.EventBusUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 *
 */
public class ShiWuSelectActivity extends BaseActivity {

    @BindView(R.id.recyclerView_type)
    RecyclerView typeRecycler;
    ShiWuTypeAdapter typeAdapter;
    YinShiMode yinShiMode;
    List<ShiWuTypeEntity> shiWuTypes;
    List<ShiWuEntity> shiWuEntities;
    List<ShiWuSelectEntity> adapterData = new ArrayList<>();
    boolean isLoaded = false;
    @BindView(R.id.contact_list)
    FoodListView foodListView;
    @BindView(R.id.search)
    EditText searchT;
    YinShiDetailAdpterEntity yinShiDetailEntity;
    String haveMealsTypeId;

    @BindView(R.id.search_recycler)
    ListView searchRecycler;
    ShiWuSearchAdapter searchAdapter;
    @BindView(R.id.content_result)
    LinearLayout contentL;

    @BindView(R.id.clear_search)
    ImageView clearSearchI;

    public static void goSelect(Context context, YinShiDetailAdpterEntity yinShiDetailEntity) {
        Intent intent = new Intent(context, ShiWuSelectActivity.class);
        intent.putExtra("yinShiDetailEntity", yinShiDetailEntity);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        yinShiDetailEntity = (YinShiDetailAdpterEntity) intent.getSerializableExtra("yinShiDetailEntity");
        haveMealsTypeId = yinShiDetailEntity.getYongCanType().getId();
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_shi_wu_select);
    }

    @Override
    protected void initView() {
        yinShiMode = new YinShiMode();
        typeAdapter = new ShiWuTypeAdapter();
        typeRecycler.setLayoutManager(new LinearLayoutManager(context));
        typeRecycler.setAdapter(typeAdapter);
        searchAdapter = new ShiWuSearchAdapter(context);
        searchRecycler.setAdapter(searchAdapter);

    }

    @Override
    protected void obtainData() {
        showLoadingDialog("加载中");
        queryType();
        queryAllFood();
    }


    @Override
    protected void initEvent() {
        initTypeEvent();
        searchT.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == event.KEYCODE_ENTER) {
                    goSearch();
                }
                return false;
            }
        });
        searchT.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && foodListView.getAdapter() != null) {
                    foodListView.getAdapter().setIndex(-1l);
                }
            }
        });
        searchT.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String c = s.toString();
                if (notEmpty(c)) {
                    if (!searchRecycler.isShown()) {
                        searchRecycler.setVisibility(View.VISIBLE);
                        contentL.setVisibility(View.GONE);
                    }
                    goSearch();
                } else {
                    if (!contentL.isShown()) {
                        searchRecycler.setVisibility(View.GONE);
                        contentL.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        clearSearchI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSearch();
            }
        });
    }


    private void goSearch() {
        if (adapterData != null) {
            String content = searchT.getText() + "";
            String contentP = Pinyin.toPinyin(content, "").toLowerCase();
            List<ShiWuEntity> result = new ArrayList<>();
            for (int i = 0; i < adapterData.size(); i++) {
                List<ShiWuEntity> data = adapterData.get(i).getData();
                for (int j = 0; j < data.size(); j++) {
                    ShiWuEntity entity = data.get(j);
                    if (entity.getPinyin().contains(contentP)) {
                        result.add(entity);
                    }
                }
            }
            searchAdapter.replaceData(result);
        }
    }


    public void save(View view) {
        if (!checkSearch()) {
            return;
        }
        List<YinShiData> list = new ArrayList<>();
        for (int i = 0; i < adapterData.size(); i++) {
            List<ShiWuEntity> data = adapterData.get(i).getData();
            for (int j = 0; j < data.size(); j++) {
                ShiWuEntity entity = data.get(j);
                if (entity.getGram() != -1) {
                    YinShiData yinShiData = new YinShiData();
                    for (YinShiDetailEntity detailEntity : yinShiDetailEntity.getYinShiDetailEntities()) {
                        // 判断患者已存在该食物
                        if ((entity.getId() + "").equals(detailEntity.getFoodId())) {
                            yinShiData.setId(detailEntity.getId());
                        }
                    }
                    yinShiData.setFoodTypeId(adapterData.get(i).getType().getId());
                    yinShiData.setFoodId(entity.getId() + "");
                    yinShiData.setGram(entity.getGram() + "");
                    yinShiData.setHaveMealsTypeId(haveMealsTypeId);
                    list.add(yinShiData);
                }
            }
        }
        YinShiSelectMessage message = new YinShiSelectMessage();
        message.setData(list);
        EventBusUtil.postEvent(message);
        finish();
    }

    private void initTypeEvent() {
        typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                typeAdapter.setSelectPosition(position);
                setTypeData(position);
            }
        });
    }

    private void queryType() {
        yinShiMode.queryShiWuType(new CommonObserver<List<ShiWuTypeEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(List<ShiWuTypeEntity> data) {
                shiWuTypes = data;
                typeAdapter.replaceData(data);
                if (isLoaded) {
                    initData();
                } else {
                    isLoaded = true;
                }
            }
        }, lifecycleSubject);
    }

    private void queryAllFood() {
        yinShiMode.queryShiWuALl(new CommonObserver<List<ShiWuEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(List<ShiWuEntity> data) {
                shiWuEntities = data;
                if (isLoaded) {
                    initData();
                } else {
                    isLoaded = true;
                }
            }
        }, lifecycleSubject);
    }


    private void initData() {
        if (shiWuTypes != null && shiWuEntities != null) {
            for (ShiWuTypeEntity typeEntity : shiWuTypes) {
                ShiWuSelectEntity selectEntity = new ShiWuSelectEntity();
                List<ShiWuEntity> list = new ArrayList<>();
                for (ShiWuEntity shiWuEntity : shiWuEntities) {
                    if ((typeEntity.getId() + "").equals(shiWuEntity.getFoodTypeId() + "")) {
                        list.add(shiWuEntity);
                    }
                }
                selectEntity.setType(typeEntity);
                selectEntity.setData(list);
                adapterData.add(selectEntity);
            }
            setTypeData(0);
        }
        dismissLoadingDialog();
    }

    public void setTypeData(int position) {
        List<ShiWuEntity> list = adapterData.get(position).getData();
        List<SlideBarEntity> list1 = new ArrayList<>();
        if (list != null) {
            for (ShiWuEntity entity : list) {
                entity.setFoodId(entity.getId());
                list1.add(entity);
            }
        }
        // 初始化数据
        foodListView.init(list1, adapterData, position, yinShiDetailEntity);
    }

    public void closeActivity(View view) {
        if (checkSearch()) {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK && !checkSearch())) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 判断搜索框是否有内容，如果没有返回true， 如果有范湖false并清除
     *
     * @return
     */
    private boolean checkSearch() {
        if (notEmpty(searchT.getText() + "")) {
            setText(searchT, "");
            CommonUtil.hideSoftInput(context, clearSearchI);
            return false;
        }
        return true;
    }

}
